﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Everynet.Models;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Net.Mail;
using Mail.Mailers;
using Mvc.Mailer;
using System.Net;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.IO;
using System.Threading;


namespace Everynet.Controllers
{
    public class signUpController : Controller
    {
        private IUserMailer _userMailer = new UserMailer();
        //
        // GET: /Welcome/

        public IUserMailer UserMailer
        {
            get { return _userMailer; }
            set { _userMailer = value; }
        }

        private EverynetEntities db = new EverynetEntities();
        //
        // GET: /signUp/

        #region[SignUp]
        public ActionResult Index()
        {
            var model = new signUpModel();
            model.listUserTypes = (from pro in db.UserTypes select new userTypesModel() { UserTypeID = pro.UserTypeID, TypeName = pro.TypeName }).ToList();
            model.SelectedTitle = getTitles();
            return View(model);
        }
        public ActionResult Signup(Int64 id)
        {
            Int64 cookieID = 0;
            if (Request.Cookies["ckUserID"] != null)
            {
                cookieID = Convert.ToInt64(Request.Cookies["ckUserID"].Value);
            }

            //if Session Expire, again retrieve value from here with cookie id.
            var getUserPassword = (from p in db.Users where p.ID == cookieID select p.Password).SingleOrDefault();
            if (Session["userPassword"] == null)
            {
                Session["userPassword"] = getUserPassword;
            }
            int checkValidUser = checkUserValid(id);
            if (checkValidUser == 1) //Valid User
            {
                var model = new signUpModel();
                model.listUserTypes = (from pro in db.UserTypes select new userTypesModel() { UserTypeID = pro.UserTypeID, TypeName = pro.TypeName }).ToList();
                model = (from e in db.Users
                         where e.ID == id
                         select new signUpModel() { ID = e.ID, FirstName = e.FirstName, LastName = e.LastName, Title = e.Title, MobileNumber = e.MobileNumber, Email = e.Email, UserTypeID = e.UserTypeID, ServiceAddress = e.ServiceAddress, ServicePhoneNumber = e.ServicePhoneNumber }).SingleOrDefault();
                model.ID = id;
                model.SelectedTitle = getTitles();
                model.SelectedTitleItem = model.Title;
                return View("Index", model);
            }

            else if (checkValidUser == -1) //session expire
            {
                return RedirectToAction("Signup", new { id = id });
            }
            else
            {
                return View("AccessDenied");
            }
        }

        public ActionResult ResumeLogin(signUpModel model)
        {

            //check User is already complete Registered.
            var chkUserCompleteRegistered = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.CompleteRegistered).FirstOrDefault();

            if (chkUserCompleteRegistered == true)
            {
                ModelState.AddModelError("", "Your signup registration is completed already.");
                return Json(new { success = -1 });
            }
            else
            {
                //check this is a valid email and password:
                var checkUserIdbyUsernamePassword = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.ID).FirstOrDefault();
                if (checkUserIdbyUsernamePassword != 0) //Valid User
                {
                    HttpCookie UserIDCookie = new HttpCookie("ckUserID");
                    UserIDCookie.Expires = DateTime.Now.AddDays(1);
                    UserIDCookie.Value = checkUserIdbyUsernamePassword.ToString();
                    Response.Cookies.Add(UserIDCookie);

                    Session["userPassword"] = model.Password;

                    return Json(new { url = Url.Action("Availability/" + checkUserIdbyUsernamePassword) });
                }
                else
                {

                    ModelState.AddModelError("", "Invalid Email and Password");
                    return Json(new { success = -2 });
                }
            }
        }


        public ActionResult AlreadywithEverynet(signUpModel model)
        {

            //check User is already complete Registered.
            var chkUserCompleteRegistered = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.CompleteRegistered).FirstOrDefault();

            if (chkUserCompleteRegistered == true)
            {

                //check this is a valid email and password:
                var checkUserIdbyUsernamePassword = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.ID).FirstOrDefault();
                if (checkUserIdbyUsernamePassword != 0) //Valid User
                {
                    HttpCookie UserIDCookie = new HttpCookie("ckUserID");
                    UserIDCookie.Expires = DateTime.Now.AddDays(1);
                    UserIDCookie.Value = checkUserIdbyUsernamePassword.ToString();
                    Response.Cookies.Add(UserIDCookie);

                    Session["userPassword"] = model.Password.ToString().Trim();

                    HttpCookie chkChangePlan = new HttpCookie("ckChangePlan");
                    chkChangePlan.Expires = DateTime.Now.AddDays(1);
                    chkChangePlan.Value = 1.ToString();
                    Response.Cookies.Add(chkChangePlan);

                    //We need to set the cookie Values also because values are already in database.
                    //Get planNameDetailID
                    var planNamesDetailID = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.PlanNamesDetailID).FirstOrDefault();
                    //Get the planID
                    var planNamesID = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == planNamesDetailID select p.PlanNamesID).FirstOrDefault();
                    var planName = (from p in db.PlanNames where p.ID == planNamesID select p.Name).FirstOrDefault();

                    #region [Handle Cookies]
                    if (Request.Cookies["MainCookie"] != null)
                    {
                        HttpCookie cookie = Request.Cookies["MainCookie"];
                        cookie.Expires = DateTime.Now.AddDays(-5);
                        Response.Cookies.Add(cookie);
                    }

                    HttpCookie cookieM = new HttpCookie("MainCookie");
                    string ck = planNamesID.ToString() + '|' + planNamesID.ToString() + '|' + planName;
                    cookieM.Value = ck;
                    cookieM.Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(cookieM);

                    #endregion

                    return Json(new { url = Url.Action("Configuration/" + checkUserIdbyUsernamePassword) });
                }
                else
                {

                    ModelState.AddModelError("", "Invalid Email and Password");
                    return Json(new { success = -2 });
                }
            }
            else
            {
                ModelState.AddModelError("", "Please first complete your signup process by selecting Resume my application.");
                return Json(new { success = -1 });
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult InsertUpdateUsers(signUpModel modelsignup)
        {
            //Fetch the Ip Address of the User.
            string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            DateTime? currentDateTime = System.DateTime.Now;

            User model = new User() { ID = modelsignup.ID, Title = modelsignup.SelectedTitleItem, FirstName = modelsignup.FirstName, LastName = modelsignup.LastName, MobileNumber = modelsignup.MobileNumber, Email = modelsignup.Email, UserTypeID = modelsignup.UserTypeID, ServiceAddress = modelsignup.ServiceAddress, ServicePhoneNumber = modelsignup.ServicePhoneNumber, RegisterDateTime = currentDateTime, IPAddress = ip };

            ModelState.Remove("UserName");
            ModelState.Remove("PlanQuotaID");
            ModelState.Remove("ADSLprovider");
            ModelState.Remove("PlanNamesDetailID");
            ModelState.Remove("ADSLproviderOther");
            ModelState.Remove("Password");
            ModelState.Remove("PlanQuotaID");
            ModelState.Remove("UserName");
            ModelState.Remove("PlanNamesID");
            if (modelsignup.ServicePhoneNumber == null)
            {
                ModelState.Remove("ServicePhoneNumber");
            }
            Int64 getID = 0;
            if (ModelState.IsValid)
            {

                if (model.ID == 0) //insert
                {
                    db.AddToUsers(model);
                    db.SaveChanges();
                    getID = model.ID;

                    HttpCookie UserIDCookie = new HttpCookie("ckUserID");
                    UserIDCookie.Expires = DateTime.Now.AddDays(1);

                    UserIDCookie.Value = getID.ToString();
                    Response.Cookies.Add(UserIDCookie);

                    #region[Generate Password and Save in User Table]
                    //password generation for user and save in database
                    string getGeneratedPassword = GenerateRandomPassword();

                    //update password in the database.
                    db.Users.Detach(model);
                    User dbUser = new User { ID = model.ID };
                    db.Users.Attach(dbUser);
                    dbUser.Password = getGeneratedPassword;
                    db.SaveChanges();
                    #endregion

                    #region[Send Email]
                    var getUserEmail = (from p in db.Users where p.ID == getID select p.Email).SingleOrDefault();
                    var getUserPassword = (from p in db.Users where p.ID == getID select p.Password).SingleOrDefault();
                    Session["userPassword"] = getUserPassword;
                    var message = "";
                    try
                    {
                        UserMailer.SignUpQuickMail(getUserEmail, "Registration Confirmation", message, getUserPassword).Send();
                    }
                    catch { }
                    #endregion
                }

                else //Update
                {
                    var result = (from e in db.Users
                                  where e.ID == model.ID
                                  select e).SingleOrDefault();
                    if (TryUpdateModel(result, new[] { "FirstName", "LastName", "Title", "MobileNumber", "Email", "UserTypeID", "ServiceAddress", "ServicePhoneNumber" }))
                    {
                        db.SaveChanges();
                        getID = model.ID;
                    }
                }
                return RedirectToAction("Availability", new { id = getID });


            }
            else
            {
                return RedirectToAction("Index");
            }

        }
        #endregion

        #region[enums]
        public enum defaultPlanID
        {
            getdefaultPlanId = 1
        }

        public enum SelectedplanId
        {
            getSelectedplanId = 1
        }
        #endregion

        #region[ Availability]
        public ActionResult Availability(Int64 id)
        {
            int checkValidUser = checkUserValid(id);
            if (checkValidUser == 1) //Valid User
            {
                var model = (from p in db.Users
                             where p.ID == id
                             select new signUpModel()
                             {
                                 ServiceAddress = p.ServiceAddress,
                                 ServicePhoneNumber = p.ServicePhoneNumber,
                                 Email = p.Email,
                                 Password = p.Password,
                                 ADSLprovider = p.ADSLprovider,
                                 ADSLproviderOther = p.ADSLproviderOther
                             }).FirstOrDefault();
                model.ID = id;
                model.SelectedADSL = (from m in db.AdslProviders
                                      select m).AsEnumerable()
                               .Select(x => new SelectListItem { Text = x.ADSLName.ToString(), Value = x.ADSLProviderID.ToString() });

                Int32 mainSelectedplanId = (int)SelectedplanId.getSelectedplanId; //fixed 1 id by default

                if (Request.Cookies["MainCookie"] != null)
                {

                    String Getvalue = Request.Cookies["MainCookie"].Value.ToString().Replace("%7C", "|").Replace("%20", " ");
                    string[] GetValue1 = Getvalue.Split('|');

                    string fValue = GetValue1[1].ToString();

                    if (fValue != null)
                    {
                        mainSelectedplanId = Convert.ToInt32(fValue);
                    }
                }


                Int32 getvalueRes = (int)Everynet.Models.signUpModel.enumPlanNames.TransACTResidential;
                Int32 getValueBusiness = (int)Everynet.Models.signUpModel.enumPlanNames.TransACTBusiness;
                Int32 getValueNaked = (int)Everynet.Models.signUpModel.enumPlanNames.NakedDSL;

                model.SelectedPlanNames = (from m in db.PlanNames
                                           where m.ID != mainSelectedplanId && m.ID != getvalueRes && m.ID != getValueBusiness && m.ID != getValueNaked
                                           select m).AsEnumerable()
                               .Select(x => new SelectListItem { Text = x.Name.ToString(), Value = x.ID.ToString() });

                return View("Availability", model);
            }

            else if (checkValidUser == -1) //session expire
            {
                return RedirectToAction("Signup", new { id = id });
            }
            else
            {
                return View("AccessDenied");
            }
        }
        //this function is called from the Jquery ajax(Availability Page)
        public void SendEmailOfNakedToUserandVendor(Int64 userID)
        {

            #region[Send Email to User and Vendor]
            var getUserEmail = (from p in db.Users where p.ID == userID select p.Email).SingleOrDefault();
            var getFirstName = (from p in db.Users where p.ID == userID select p.FirstName).SingleOrDefault();
            var getLastName = (from p in db.Users where p.ID == userID select p.LastName).SingleOrDefault();
            var getServicePhoneNumber = (from p in db.Users where p.ID == userID select p.ServicePhoneNumber).SingleOrDefault().ToString();
            var fullName = getFirstName + ' ' + getLastName;
            var VendorEmailforNakedDSL = ConfigurationManager.AppSettings["VendorEmailforNakedDSL"].ToString();
            try
            {
                UserMailer.NakedNotifyToUser(getUserEmail, "Naked SQ: Service Qualification").Send();
                UserMailer.NakedNotifyToVendor(VendorEmailforNakedDSL, "Naked SQ: Customer Name - Contact#", getUserEmail, fullName, getServicePhoneNumber).Send();
            }
            catch { }
            #endregion
        }
        //this function is called from the Jquery ajax(Availability Page)
        public void SendEmailtoEverynetIfQualificationFail(Int64 userID)
        {
            #region[Send Email to Everynet]
            var getUserEmail = (from p in db.Users where p.ID == userID select p.Email).SingleOrDefault();
            var getFirstName = (from p in db.Users where p.ID == userID select p.FirstName).SingleOrDefault();
            var getLastName = (from p in db.Users where p.ID == userID select p.LastName).SingleOrDefault();
            var getServicePhoneNumber = (from p in db.Users where p.ID == userID select p.ServicePhoneNumber).SingleOrDefault().ToString();
            var fullName = getFirstName + ' ' + getLastName;
            var QualificationFailSignupMail = ConfigurationManager.AppSettings["QualificationFailSignupEmail"].ToString();
            try
            {
                UserMailer.QualificationFail(QualificationFailSignupMail, "Service Qualification Fail for User", getUserEmail, fullName, getServicePhoneNumber).Send();
            }
            catch { }

            #endregion

        }
        [HttpPost]
        public ActionResult UpdateAvailability(Int64 ID, Int32? ADSLProvider, String ADSLProviderOther)
        {
            var getResult = 1;
            User dbUser = new User { ID = ID };
            db.Users.Attach(dbUser);
            dbUser.ADSLprovider = ADSLProvider;
            dbUser.ADSLproviderOther = ADSLProviderOther;
            db.SaveChanges();
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region[Configuration]
        public ActionResult Configuration(Int64 id)
        {
            int checkValidUser = checkUserValid(id);
            if (checkValidUser == 1) //Valid User
            {

                var PlanID = (int)defaultPlanID.getdefaultPlanId; //fixed 1 by default

                if (Request.Cookies["MainCookie"] != null)
                {

                    String Getvalue = Request.Cookies["MainCookie"].Value.ToString().Replace("%7C", "|").Replace("%20", " ");
                    string[] GetValue1 = Getvalue.Split('|');

                    string fValue = GetValue1[0].ToString();

                    if (fValue != null)
                    {
                        PlanID = Convert.ToInt32(fValue);
                    }
                }
                #region check user table have PlanNamesDetailID , if exits then use that otherwise use first value by default.
                Int32 chkPlanNamesDetailID = Convert.ToInt32((from u in db.Users where u.ID == id select u.PlanNamesDetailID).SingleOrDefault());
                Int32 TopPlanNamesDetailsID=0;
                if (chkPlanNamesDetailID == 0) //Value not exists , Insert Case
                {
                    TopPlanNamesDetailsID = (from plan in db.PlanNamesDetails where plan.PlanNamesID == PlanID && plan.VisiblePublic == true orderby plan.Price ascending select plan.PlanNamesDetailID).FirstOrDefault();
                }
                else //Value  exists , Update Case
                {
                    TopPlanNamesDetailsID = chkPlanNamesDetailID;
                }
                #endregion
               

                var model = new signUpModel();
                model.listUserTypes = (from pro in db.UserTypes select new userTypesModel() { UserTypeID = pro.UserTypeID, TypeName = pro.TypeName }).ToList();
                model = (from e in db.Users where e.ID == id select new signUpModel() { ID = e.ID, FirstName = e.FirstName, LastName = e.LastName, Title = e.Title, MobileNumber = e.MobileNumber, Email = e.Email, UserTypeID = e.UserTypeID, ServiceAddress = e.ServiceAddress, ServicePhoneNumber = e.ServicePhoneNumber, UserName = e.UserName, ADSLprovider = e.ADSLprovider, PlanNamesDetailID = e.PlanNamesDetailID, PlanQuotaID = e.PlanQuotaID, ADSLproviderOther = e.ADSLproviderOther, DirectoryListingID = e.DirectoryListingID, ConnectionMethodID = e.ConnectionMethodID }).SingleOrDefault();
                model.ID = id;
                model.SelectedTitle = getTitles();
                //ADSL Provider
                model.SelectedADSL = (from m in db.AdslProviders
                                      select m).AsEnumerable()
                                 .Select(x => new SelectListItem { Text = x.ADSLName.ToString(), Value = x.ADSLProviderID.ToString() });

                model.SelectedTitleItem = model.Title;
                //Bind Plan grid.
                model.listPlanDetail = (from plan in db.PlanNamesDetails where plan.PlanNamesID == PlanID && plan.VisiblePublic == true orderby plan.Price ascending select new PlanDetailModel() { PlanNamesDetailID = plan.PlanNamesDetailID, PlanDetailName = plan.PlanDetailName, PlanDetailQuota = plan.PlanDetailQuota, Price = plan.Price, PlanNamesID = plan.PlanNamesID }).ToList();
                model.Name = (from p in db.PlanNames where p.ID == PlanID select p.Name).SingleOrDefault();
                //Contract Length
               // model.listPlanQuotaModel = (from q in db.PlanQuotas where q.VisiblePublic == true && q.PlanNamesID == PlanID orderby q.PlanQuotaValue ascending select new PlanQuotaModel() { PlanQuotaID = q.PlanQuotaID, PlanQuotaValue = q.PlanQuotaValue, PlanQuotaInterval = q.PlanQuotaInterval, SetupCost = q.SetupCost }).ToList();

                model.listPlanQuotaModel = (from q in db.PlanQuotas where q.VisiblePublic == true && q.PlanNamesDetailID == TopPlanNamesDetailsID orderby q.PlanQuotaValue ascending select new PlanQuotaModel() { PlanQuotaID = q.PlanQuotaID, PlanQuotaValue = q.PlanQuotaValue, PlanQuotaInterval = q.PlanQuotaInterval, SetupCost = q.SetupCost, EarlyExitFee=q.EarlyExitFee, Comment=q.Comment }).ToList();
                //Extra Contract Length
                #region  Extra Contract Length
                var SubExtrasDetails = (from SE in db.SubExtrasDetails where SE.VisiblePublic == true select SE).ToList();
                if (chkPlanNamesDetailID == 0) //Value not exists , Insert Case
                {
                    List<int> distinctListfirst = SubExtrasDetails.GroupBy(x => x.SubExtrasID)
                           .Select(g => g.First().SubExtrasDetailID)
                           .ToList();
                    List<int?> distinctList = distinctListfirst.ConvertAll(x => (int?)x);
                    model.listExtraPlanQuotaModel = (from q in db.ExtraPlanQuotas
                                                     where distinctList.Contains(q.SubExtrasDetailID) && q.VisiblePublic == true
                                                     orderby q.ExtraPlanQuotaValue ascending
                                                     select new ExtraPlanQuotaModel()
                                                     {
                                                         ExtraPlanQuotaID = q.ExtraPlanQuotaID,
                                                         ExtraPlanQuotaValue = q.ExtraPlanQuotaValue,
                                                         ExtraPlanQuotaInterval = q.ExtraPlanQuotaInterval,
                                                         ExtraSetupCost = q.ExtraSetupCost,
                                                         SubExtrasID = q.SubExtrasID,
                                                         SubExtrasDetailID = q.SubExtrasDetailID
                                                     }).ToList();
                }
                else //Value  exists , Update Case
                {
                    var SubExtrasDetailAssignToUsers = (from SE in db.SubExtrasDetailAssignToUsers where SE.UserID==id select new SubExtraDetailModel(){SubExtrasDetailID=SE.SubExtrasDetailID}).ToList();
                    List<int?> SubExtrasDetailAssignToUsersH = new List<int?>();
                    foreach (var getsingleValue in SubExtrasDetailAssignToUsers)
                    {
                        SubExtrasDetailAssignToUsersH.Add(getsingleValue.SubExtrasDetailID); //[42,43]
                    }
                    
                    model.listExtraPlanQuotaModel = (from q in db.ExtraPlanQuotas
                                                     where SubExtrasDetailAssignToUsersH.Contains(q.SubExtrasDetailID) && q.VisiblePublic == true
                                                     orderby q.ExtraPlanQuotaValue ascending
                                                     select new ExtraPlanQuotaModel()
                                                     {
                                                         ExtraPlanQuotaID = q.ExtraPlanQuotaID,
                                                         ExtraPlanQuotaValue = q.ExtraPlanQuotaValue,
                                                         ExtraPlanQuotaInterval = q.ExtraPlanQuotaInterval,
                                                         ExtraSetupCost = q.ExtraSetupCost,
                                                         SubExtrasID = q.SubExtrasID,
                                                         SubExtrasDetailID = q.SubExtrasDetailID
                                                     }).ToList();
                }
                #endregion
                //change:13.05.2013
                //If they select national, or regional, a bnundled telephone line is an option
                //in those two cases telephone line,hardware and voip is an extras.
                //for naked, and Transact, only hardware and voip extras.

                //Remove Telephone
                //List<int> lstextraIDS = new List<int>(new int[] { (int)(signUpModel.enumExtras.Telephony), (int)(signUpModel.enumExtras.VOIP), (int)(signUpModel.enumExtras.HardwareOptions) });
                List<int> lstextraIDS = new List<int>(new int[] { (int)(signUpModel.enumExtras.VOIP), (int)(signUpModel.enumExtras.HardwareOptions) });
                if ((PlanID == (int)(signUpModel.enumPlanNames.NationalADSL2)) || (PlanID == (int)(signUpModel.enumPlanNames.RegionalADSL2)) || (PlanID == (int)(signUpModel.enumPlanNames.BundleADSLHomephone)) || (PlanID == (int)(signUpModel.enumPlanNames.BundleADSLVOIP)) || (PlanID == (int)(signUpModel.enumPlanNames.BundleADSLHomephonePlusVOIP)) || (PlanID == (int)(signUpModel.enumPlanNames.NBNFibre12MDownload)) || (PlanID == (int)(signUpModel.enumPlanNames.NBNFibre25MDownload)) || (PlanID == (int)(signUpModel.enumPlanNames.NBNFibre50MDownload)) || (PlanID == (int)(signUpModel.enumPlanNames.NBNFibre100MDownload)))
                {
                    //lstextraIDS = new List<int>(new int[] { (int)(signUpModel.enumExtras.Telephony), (int)(signUpModel.enumExtras.VOIP), (int)(signUpModel.enumExtras.HardwareOptions) });
                   //Remove Telephone
                    lstextraIDS = new List<int>(new int[] {(int)(signUpModel.enumExtras.VOIP), (int)(signUpModel.enumExtras.HardwareOptions) });
                }
                else if ((PlanID == (int)(signUpModel.enumPlanNames.NakedDSL)) || (PlanID == (int)(signUpModel.enumPlanNames.TransACTResidential)) || (PlanID == (int)(signUpModel.enumPlanNames.TransACTBusiness)))
                {
                    lstextraIDS = new List<int>(new int[] { (int)(signUpModel.enumExtras.VOIP), (int)(signUpModel.enumExtras.HardwareOptions) });

                }
                #region[SubExtras and SubExtras Detail]
                model.listSubExtraModel = from SE in db.SubExtras
                                          where lstextraIDS.Contains((int)SE.ExtrasID)
                                          select new SubExtraDetailModel()
                                          {
                                              SubExtrasID = (Int32?)SE.SubExtrasID,
                                              SubExtrasName = SE.SubExtrasName
                                          };

                model.listSubExtraDetailModel = from SE in db.SubExtras
                                                join SED in db.SubExtrasDetails on new { SubExtrasID = SE.SubExtrasID } equals new { SubExtrasID = (Int32)SED.SubExtrasID }
                                                where lstextraIDS.Contains((int)SE.ExtrasID) && SED.VisiblePublic == true

                                                select new SubExtraDetailModel()
                                                {
                                                    SubExtrasID = (Int32?)SED.SubExtrasID,
                                                    SubExtrasDetailName = SED.SubExtrasDetailName,
                                                    SubExtrasDetailPrice = SED.SubExtrasDetailPrice,
                                                    SubExtrasDetailID = SED.SubExtrasDetailID
                                                };
                #endregion
                #region[Hardware]
                model.listSubHardwareDetailModel = from SE in db.SubHardwares
                                                   join SED in db.SubHardwaresDetails on new { SubHardwareID = SE.SubHardwareID } equals new { SubHardwareID = (Int32)SED.SubHardwareID }
                                                   where SED.VisiblePublic == true
                                                   select new SubHardwareDetailModel()
                                                   {
                                                       SubHardwareID = (Int32?)SED.SubHardwareID,
                                                       SubHardwareDetailName = SED.SubHardwareDetailName,
                                                       SubHardwareDetailPrice = SED.SubHardwareDetailPrice,
                                                       SubHardwareDetailID = SED.SubHardwareDetailID
                                                   };

                model.listSubHardwareModel = from SE in db.SubHardwares
                                             select new SubHardwareDetailModel()
                                             {
                                                 SubHardwareID = (Int32?)SE.SubHardwareID,
                                                 SubHardwareName = SE.SubHardwareName
                                             };
                #endregion
               
                #region[Hardware Detail= code to get user selected Hardwares]
                //We need to create an Array of SubExtras first(SubExtrasDetailID) according to selected plantype and then  Replace the user selected values.  
                var getArrayofSubextrasH = (from SE in db.SubHardwares
                                           where SE.VisiblePublic==true
                                           select new SubHardwareDetailModel()
                                           {
                                               SubHardwareID = SE.SubHardwareID,
                                           }).ToList();  //[13,14]

                //selected value that user selected and save in database  [39,40]
                var getSelectedExtrasH = (from ext in db.SubHardwareDetailAssignToUsers where ext.UserID == id select new SubHardwareDetailModel() { SubHardwareDetailID = ext.SubHardwaresDetailID }).ToList();
                List<int> getSelectedExtrasnewH = new List<int>();
                foreach (var getsingleValue in getSelectedExtrasH)
                {
                    getSelectedExtrasnewH.Add(getsingleValue.SubHardwareDetailID); //[42,43]
                }

                //selected user values-- Sub Extra detail for Matching
                var getSubExtrasDetailsH = from SED in db.SubHardwaresDetails
                                           where getSelectedExtrasnewH.Contains(SED.SubHardwareDetailID)
                                           select new SubHardwareDetailModel()
                                          {
                                              SubHardwareID = SED.SubHardwareID,
                                              SubHardwareDetailID = SED.SubHardwareDetailID
                                          }; //[42,43//13,13]
                foreach (var getArrayofSubextrasSingle in getArrayofSubextrasH) //[42,43]
                 {
                    string check = String.Empty;
                    foreach (var getSubExtrasDetailsSingle1 in getSubExtrasDetailsH) //[42,43//13,13]
                    {
                        if (getArrayofSubextrasSingle.SubHardwareID == getSubExtrasDetailsSingle1.SubHardwareID)
                        {
                            //we need to find the qty with SubhardwaredetailId and userID
                            Int32 detailId=Convert.ToInt32(getSubExtrasDetailsSingle1.SubHardwareDetailID.ToString());
                            Int32 Qty = (from Q in db.SubHardwareDetailAssignToUsers
                                       where Q.UserID == id && Q.SubHardwaresDetailID == detailId
                                       select Q.Quantity).SingleOrDefault();
                            string stringfinal = detailId.ToString() + "&" + Qty +"#";
                            check += stringfinal;
                        }

                    }
                    if (!String.IsNullOrEmpty(check))
                    {
                        model.strSubHardwareDetailID += check.Substring(0, check.Length - 1) + ",";
                    }
                    else
                    {
                        //if update case then set 0, else set '|'
                        var checkADSLProvider = (from ext in db.Users where ext.ID == id select ext.ADSLprovider).SingleOrDefault();
                        if ((String.IsNullOrEmpty(checkADSLProvider.ToString())) || (checkADSLProvider.ToString() == "0"))
                        {
                            model.strSubHardwareDetailID += "|" + ",";
                        }
                        else
                        {
                            model.strSubHardwareDetailID += "0" + ",";
                        }

                    }

                }
                #endregion
               
                #region [Sub Extras= Code to get user selected Extras]
                //We need to create an Array of SubExtras first(SubExtrasDetailID) according to selected plantype and then  Replace the user selected values.  
                var getArrayofSubextras = (from SE in db.SubExtras
                                           where lstextraIDS.Contains((int)SE.ExtrasID)
                                           select new SubExtraDetailModel()
                                                  {
                                                      SubExtrasID = SE.SubExtrasID,
                                                  }).ToList();  //[6,7,11,12]

                //selected value that user selected and save in database  [39,40]
                var getSelectedExtras = (from ext in db.SubExtrasDetailAssignToUsers where ext.UserID == id select new SubExtraDetailModel() { SubExtrasDetailID = ext.SubExtrasDetailID }).ToList();
                List<int> getSelectedExtrasnew = new List<int>();
                foreach (var getsingleValue in getSelectedExtras)
                {
                    getSelectedExtrasnew.Add(getsingleValue.SubExtrasDetailID);
                }

                //selected user values-- Sub Extra detail for Matching
                var getSubExtrasDetails = from SED in db.SubExtrasDetails
                                          where getSelectedExtrasnew.Contains(SED.SubExtrasDetailID)
                                          select new SubExtraDetailModel()
                                                {
                                                    SubExtrasID = SED.SubExtrasID,
                                                    SubExtrasDetailID = SED.SubExtrasDetailID
                                                };

                String getArray = String.Empty;

                foreach (var getArrayofSubextrasSingle in getArrayofSubextras) //[6,7,11,12]
                {
                    string check = String.Empty;
                    foreach (var getSubExtrasDetailsSingle1 in getSubExtrasDetails) //[39,40]
                    {
                        if (getArrayofSubextrasSingle.SubExtrasID == getSubExtrasDetailsSingle1.SubExtrasID)
                        {

                            check = getSubExtrasDetailsSingle1.SubExtrasDetailID.ToString();
                        }

                    }
                    if (!String.IsNullOrEmpty(check))
                    {
                        model.strSubExtrasDetailID += check + ",";
                    }
                    else
                    {
                        //if update case then set 0, else set '|'
                        var checkADSLProvider = (from ext in db.Users where ext.ID == id select ext.ADSLprovider).SingleOrDefault();
                        if ((String.IsNullOrEmpty(checkADSLProvider.ToString())) || (checkADSLProvider.ToString() == "0"))
                        {
                            model.strSubExtrasDetailID += "|" + ",";
                        }
                        else
                        {
                            model.strSubExtrasDetailID += "0" + ",";
                        }

                    }

                }

                #endregion
                #region [Sub Extras Contract= Code to get user Selected extras contract]
                //We need to create an Array of SubExtras first(SubExtrasDetailID) according to selected plantype and then  Replace the user selected values.
                var getArrayofSubextrasQuota = (from SE in db.SubExtras
                                                where lstextraIDS.Contains((int)SE.ExtrasID)
                                                select new SubExtraDetailModel()
                                                {
                                                    SubExtrasID = SE.SubExtrasID,
                                                }).ToList();  //[6,7,11,12]

                //selected value that user selected and save in database  [5]
                var getSelectedExtrasQuota = (from ext in db.ExtraPlanQuotaAssigntoUsers where ext.UserID == id select new ExtraPlanQuotaModel() { ExtraPlanQuotaID = ext.ExtraPlanQuotaID }).ToList();
                List<int> getSelectedExtrasnewQuota = new List<int>();
                foreach (var getsingleValueQuota in getSelectedExtrasQuota)
                {
                    getSelectedExtrasnewQuota.Add(getsingleValueQuota.ExtraPlanQuotaID);
                }
                //selected user values-- Sub Extra detail for Matching
                var getSubExtrasDetailsQuota = from SED in db.ExtraPlanQuotas
                                               where getSelectedExtrasnewQuota.Contains(SED.ExtraPlanQuotaID)
                                               select new ExtraPlanQuotaModel()
                                          {
                                              SubExtrasID = SED.SubExtrasID,
                                              ExtraPlanQuotaID = SED.ExtraPlanQuotaID
                                          };

                String getArrayQuota = String.Empty;

                foreach (var getArrayofSubextrasSingleQuota in getArrayofSubextrasQuota) //[6,7,11,12]
                {
                    string checkQuota = String.Empty;
                    foreach (var getSubExtrasDetailsSingle1Quota in getSubExtrasDetailsQuota) //[39,40]
                    {
                        if (getArrayofSubextrasSingleQuota.SubExtrasID == getSubExtrasDetailsSingle1Quota.SubExtrasID)
                        {

                            checkQuota = getSubExtrasDetailsSingle1Quota.ExtraPlanQuotaID.ToString();
                        }

                    }
                    if (!String.IsNullOrEmpty(checkQuota))
                    {
                        model.strExtraPlanQuotaID += checkQuota + ",";
                    }
                    else
                    {
                        //if update case then set 0, else set '|'
                        var checkADSLProvider = (from ext in db.Users where ext.ID == id select ext.ADSLprovider).SingleOrDefault();
                        if ((String.IsNullOrEmpty(checkADSLProvider.ToString())) || (checkADSLProvider.ToString() == "0"))
                        {
                            model.strExtraPlanQuotaID += "|" + ",";
                        }
                        else
                        {
                            model.strExtraPlanQuotaID += "0" + ",";
                        }
                    }

                }
                 #endregion
                #region//DirectoryListing/ConnectionMethod
                model.SelectedDirectoryListing = (from m in db.DirectoryListings
                                                  select m).AsEnumerable()
                                   .Select(x => new SelectListItem { Text = x.Name.ToString(), Value = x.DirectoryListingID.ToString() });
                model.SelectedConnectionMethod = (from m in db.ConnectionMethods
                                                  select m).AsEnumerable()
                                  .Select(x => new SelectListItem { Text = x.Name.ToString(), Value = x.ConnectionMethodID.ToString() });
                #endregion
                return View("Configuration", model);
            }

            else if (checkValidUser == -1) //session expire
            {
                return RedirectToAction("Signup", new { id = id });
            }
            else
            {
                return View("AccessDenied");
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConfigurationUpdateUsers(signUpModel modelsignup)
        {
            #region[Extras Quota]
            // empty or null means.. no extra is selected by the user
            if (!String.IsNullOrEmpty(modelsignup.strExtraPlanQuotaID))
            {

                var lstSubExtrasID = modelsignup.strExtraPlanQuotaID.Split(',').ToList();

                //Delete Values If Already Exists in Database by UserID
                var result = (from e in db.ExtraPlanQuotaAssigntoUsers
                              where e.UserID == modelsignup.ID
                              select e).ToList();
                foreach (var varSresult in result)
                {
                    var resultdelete = (from e in db.ExtraPlanQuotaAssigntoUsers
                                        where e.ExtraPlanQuotaAssignToUserID == varSresult.ExtraPlanQuotaAssignToUserID
                                        select e).SingleOrDefault();

                    db.DeleteObject(resultdelete);
                    db.SaveChanges();
                }

                var lstSubExtrasIDParent = modelsignup.strSubExtrasDetailID.Split(',').ToArray();
                Int32 i = 0;
                foreach (var varSubExtrasID in lstSubExtrasID)
                {
                    if (!String.IsNullOrEmpty(varSubExtrasID) && varSubExtrasID != "0")
                    {
                        var SubExtrasDetailIDGet = Convert.ToInt32(lstSubExtrasIDParent[i]);
                        Int32 getSubExtrasID = Convert.ToInt32(varSubExtrasID);
                        ExtraPlanQuotaAssigntoUser modelUser = new ExtraPlanQuotaAssigntoUser() { UserID = modelsignup.ID, ExtraPlanQuotaID = getSubExtrasID, SubExtrasDetailID = SubExtrasDetailIDGet };
                        db.AddToExtraPlanQuotaAssigntoUsers(modelUser);
                        db.SaveChanges();

                    }
                    i++;
                }
            }
            #endregion
            #region[Extras]
            // empty or null means.. no extra is selected by the user
            if (!String.IsNullOrEmpty(modelsignup.strSubExtrasDetailID))
            {
                var lstSubExtrasID = modelsignup.strSubExtrasDetailID.Split(',').ToList();

                //Delete Values If Already Exists in Database by UserID
                var result = (from e in db.SubExtrasDetailAssignToUsers
                              where e.UserID == modelsignup.ID
                              select e).ToList();
                foreach (var varSresult in result)
                {
                    var resultdelete = (from e in db.SubExtrasDetailAssignToUsers
                                        where e.SubExtrasDetailAssigntoUserID == varSresult.SubExtrasDetailAssigntoUserID
                                        select e).SingleOrDefault();

                    db.DeleteObject(resultdelete);
                    db.SaveChanges();
                }

                foreach (var varSubExtrasID in lstSubExtrasID)
                {
                    if (!String.IsNullOrEmpty(varSubExtrasID) && varSubExtrasID != "0")
                    {
                        Int32 getSubExtrasID = Convert.ToInt32(varSubExtrasID);
                        SubExtrasDetailAssignToUser modelUser = new SubExtrasDetailAssignToUser() { UserID = modelsignup.ID, SubExtrasDetailID = getSubExtrasID };
                        db.AddToSubExtrasDetailAssignToUsers(modelUser);
                        db.SaveChanges();

                    }
                }
            }
            #endregion
            #region[Hardwares]
            // empty or null means.. no extra is selected by the user
            if (!String.IsNullOrEmpty(modelsignup.strSubHardwareDetailID))
            {
                var lstSubExtrasID = modelsignup.strSubHardwareDetailID.Split(',').ToList();

                //Delete Values If Already Exists in Database by UserID
                var result = (from e in db.SubHardwareDetailAssignToUsers //dbo.SubHardwareDetailAssignToUsers
                              where e.UserID == modelsignup.ID
                              select e).ToList();
                foreach (var varSresult in result)
                {
                    var resultdelete = (from e in db.SubHardwareDetailAssignToUsers
                                        where e.SubHardwareDetailAssigntoUserID == varSresult.SubHardwareDetailAssigntoUserID
                                        select e).SingleOrDefault();

                    db.DeleteObject(resultdelete);
                    db.SaveChanges();
                }

                foreach (var varSubExtrasID in lstSubExtrasID)
                {
                    if (!String.IsNullOrEmpty(varSubExtrasID) && varSubExtrasID != "0")
                    {
                        var lstSubHardwareSplit = varSubExtrasID.Split('#').ToList();
                        foreach (var varlstSubHardwareSplit in lstSubHardwareSplit)
                        {
                            if (!String.IsNullOrEmpty(varlstSubHardwareSplit))
                            {
                                Int32 SubHardwaresDetailIDV = Convert.ToInt32(varlstSubHardwareSplit.Split('&')[0].ToString());
                                Int32 QutV = Convert.ToInt32(varlstSubHardwareSplit.Split('&')[1].ToString());

                                SubHardwareDetailAssignToUser modelUserH = new SubHardwareDetailAssignToUser() { UserID = modelsignup.ID, SubHardwaresDetailID = SubHardwaresDetailIDV, Quantity = QutV };
                                db.AddToSubHardwareDetailAssignToUsers(modelUserH);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            #endregion
            #region [User Data Save]
            User model = new User() { ID = modelsignup.ID, Title = modelsignup.SelectedTitleItem, FirstName = modelsignup.FirstName, LastName = modelsignup.LastName, MobileNumber = modelsignup.MobileNumber, Email = modelsignup.Email, UserTypeID = modelsignup.UserTypeID, ServiceAddress = modelsignup.ServiceAddress, ServicePhoneNumber = modelsignup.ServicePhoneNumber, UserName = modelsignup.UserName, ADSLprovider = modelsignup.ADSLprovider, PlanNamesDetailID = modelsignup.PlanNamesDetailID, PlanQuotaID = modelsignup.PlanQuotaID, ADSLproviderOther = modelsignup.ADSLproviderOther, DirectoryListingID = modelsignup.DirectoryListingID, ConnectionMethodID = modelsignup.ConnectionMethodID };
            model.Title = modelsignup.SelectedTitleItem;
            ModelState.Remove("Password");
            ModelState.Remove("PlanNamesID");
            if (model.ServicePhoneNumber == null)
            {
                ModelState.Remove("ServicePhoneNumber");
            }
            Int64 getID = 0;
            if (ModelState.IsValid)
            {

                var result = (from e in db.Users
                              where e.ID == model.ID
                              select e).SingleOrDefault();
                if (TryUpdateModel(result, new[] { "FirstName", "LastName", "Title", "MobileNumber", "Email", "UserTypeID", "ServiceAddress", "ServicePhoneNumber", "UserName", "ADSLprovider", "PlanNamesDetailID", "PlanQuotaID", "ADSLproviderOther", "DirectoryListingID", "ConnectionMethodID" }))
                {
                    db.SaveChanges();
                    getID = model.ID;
                }

                return RedirectToAction("OrderSummary", new { id = getID });
            }
            else
            {
                return RedirectToAction("Configuration", new { id = modelsignup.ID });
            }
            #endregion
        }
        #endregion

        #region[Order Summary]
        public ActionResult OrderSummary(Int64 id)
        {

            int checkValidUser = checkUserValid(id);
            if (checkValidUser == 1) //Valid User
            {
                var model = (from U in db.Users
                             join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID }
                             join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID }
                             join PN in db.PlanNames on new { ID = PND.PlanNamesID } equals new { ID = PN.ID }
                             where
                               U.ID == id
                             select new SummaryModel()
                             {
                                 ID = id,
                                 Name = PN.Name,
                                 ServicePhoneNumber = U.ServicePhoneNumber,
                                 PlanDetailName = PND.PlanDetailName,
                                 PlanQuotaValue = PQ.PlanQuotaValue,
                                 PlanQuotaInterval = PQ.PlanQuotaInterval,
                                 SetupCost = PQ.SetupCost,
                                 Price = PND.Price,
                                 TotalCost = (System.Decimal?)((PND.Price * PQ.PlanQuotaValue) + PQ.SetupCost)
                             }).SingleOrDefault();



                model.listSummaryModel = from SEDA in db.SubExtrasDetailAssignToUsers
                                         join SED in db.SubExtrasDetails on SEDA.SubExtrasDetailID equals SED.SubExtrasDetailID
                                         join SE in db.SubExtras on new { SubExtrasID = (Int32)SED.SubExtrasID } equals new { SubExtrasID = SE.SubExtrasID }
                                         join EPQU in db.ExtraPlanQuotaAssigntoUsers
                                               on new { SED.SubExtrasDetailID, SEDA.UserID }
                                           equals new { EPQU.SubExtrasDetailID, EPQU.UserID }
                                         join EX in db.ExtraPlanQuotas on EPQU.ExtraPlanQuotaID equals EX.ExtraPlanQuotaID
                                         where
                                           SEDA.UserID == id
                                         select new SubExtraDetailModel()
                                        {

                                            SubExtrasDetailID = (Int32)SEDA.SubExtrasDetailID,
                                            SubExtrasDetailName = SED.SubExtrasDetailName,
                                            SubExtrasDetailPrice = SED.SubExtrasDetailPrice,
                                            SubExtrasName = SE.SubExtrasName,
                                            SubExtrasSetupFee = EX.ExtraSetupCost,
                                            ExtraPlanQuotaValue = EX.ExtraPlanQuotaValue,
                                            ExtraPlanQuotaInterval = EX.ExtraPlanQuotaInterval,
                                        };

                model.listSummaryHardwareModel=from SEDA in db.SubHardwareDetailAssignToUsers
                                         join SED in db.SubHardwaresDetails on SEDA.SubHardwaresDetailID equals SED.SubHardwareDetailID
                                         join SE in db.SubHardwares on new { SubHardwareID = (Int32)SED.SubHardwareID } equals new { SubHardwareID = SE.SubHardwareID }
                                          where
                                           SEDA.UserID == id
                                               select new SubHardwareDetailModel()
                                               {

                                                   SubHardwareDetailID = (Int32)SEDA.SubHardwaresDetailID,
                                                   SubHardwareDetailName = SED.SubHardwareDetailName,
                                                   SubHardwareDetailPrice = SED.SubHardwareDetailPrice,
                                                   SubHardwareName = SE.SubHardwareName,
                                                   Quantity = SEDA.Quantity,
                                                   SubHardwareDetail=SE.SubHardwareDetail
                                               };

                return View("OrderSummary", model);
            }

            else if (checkValidUser == -1) //session expire
            {
                return RedirectToAction("Signup", new { id = id });
            }
            else
            {
                return View("AccessDenied");
            }
        }
        #endregion

        #region[Agreement]
        public ActionResult Agreement(Int64 id)
        {
            int checkValidUser = checkUserValid(id);
            if (checkValidUser == 1) //Valid User
            {

                var PlanID = (int)defaultPlanID.getdefaultPlanId; //fixed 1 by default

                if (Request.Cookies["MainCookie"] != null)
                {

                    String Getvalue = Request.Cookies["MainCookie"].Value.ToString().Replace("%7C", "|").Replace("%20", " ");
                    string[] GetValue1 = Getvalue.Split('|');

                    string fValue = GetValue1[0].ToString();

                    if (fValue != null)
                    {
                        PlanID = Convert.ToInt32(fValue);
                    }
                }
                var model = new AgreementModel();
               
                model.Agreement = (from p in db.PlanNames where p.ID == PlanID select p.Agreement).SingleOrDefault();
                model.ID = id;
                //change 13.05.2013

                List<int> lstSubExtrasDetailID = (from item in db.SubExtrasDetailAssignToUsers where item.UserID == id select item.SubExtrasDetailID).ToList();
                List<int?> lstsubextrasID = (from SE in db.SubExtrasDetails
                                             where lstSubExtrasDetailID.Contains(SE.SubExtrasDetailID)
                                             select SE.SubExtrasID
                                         ).ToList();
                model.listDynamicAgreement = from SE in db.SubExtras
                                             where lstsubextrasID.Contains(SE.SubExtrasID)
                                             select new DynamicAgreementModel()
                                            {
                                                Agreement = SE.Agreement,
                                                SubExtrasname = SE.SubExtrasName

                                            };
                List<int> lstSubExtrasDetailIDH = (from item in db.SubHardwareDetailAssignToUsers where item.UserID == id select item.SubHardwaresDetailID).ToList();
                List<int?> lstsubextrasIDH = (from SE in db.SubHardwaresDetails
                                              where lstSubExtrasDetailIDH.Contains(SE.SubHardwareDetailID)
                                             select SE.SubHardwareID
                                         ).ToList();
                model.listDynamicAgreementHardware = from SE in db.SubHardwares
                                                     where lstsubextrasIDH.Contains(SE.SubHardwareID)
                                             select new DynamicAgreementModel()
                                             {
                                                 Agreement = SE.Agreement,
                                                 SubHardwareName = SE.SubHardwareName
                                             };

                return View("Agreement", model);
            }
            else if (checkValidUser == -1) //session expire
            {
                return RedirectToAction("Signup", new { id = id });
            }
            else
            {
                return View("AccessDenied");
            }
        }
        #endregion

        #region[Order Complete]
        [ValidateAntiForgeryToken]
        public ActionResult OrderComplete(AgreementModel model)
        {
            var GetUserID = model.ID;
            if (GetUserID == 0)
            {
                if (Request.Cookies["ckUserID"] != null)
                {
                    GetUserID = Convert.ToInt64(Request.Cookies["ckUserID"].Value);
                }
            }

            //After refresh page- function not run again.(check user have already password)
            var checkUserPasswordExists = (from p in db.Users where p.ID == GetUserID select p.CompleteRegistered).FirstOrDefault();

            //Get user Email by ID
            var getUserEmail = (from p in db.Users where p.ID == GetUserID select p.Email).SingleOrDefault();
            string message = (from p in db.Users where p.ID == GetUserID select p.Password).SingleOrDefault();
            var passModel = new signUpModel();

            //get User Information
            passModel.listSignUpDetail = (from U in db.Users
                                          join UT in db.UserTypes on U.UserTypeID equals UT.UserTypeID
                                          join AP in db.AdslProviders on new { ADSLProviderID = (Int32)U.ADSLprovider } equals new { ADSLProviderID = AP.ADSLProviderID } into AP_join
                                          from AP in AP_join.DefaultIfEmpty()
                                          join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID } into PND_join
                                          from PND in PND_join.DefaultIfEmpty()
                                          join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID } into PQ_join
                                          from PQ in PQ_join.DefaultIfEmpty()
                                          where U.ID == GetUserID
                                          orderby U.ID descending
                                          select new signUpModel()
                                          {
                                              ID = U.ID,
                                              Title = U.Title,
                                              FirstName = U.FirstName,
                                              LastName = U.LastName,
                                              MobileNumber = U.MobileNumber,
                                              Email = U.Email,
                                              ADSLName = AP.ADSLName,
                                              ServiceAddress = U.ServiceAddress,
                                              ServicePhoneNumber = U.ServicePhoneNumber,
                                              UserName = U.UserName,
                                              ADSLprovider = (Int32?)U.ADSLprovider,
                                              PlanNamesDetailID = (Int32?)U.PlanNamesDetailID,
                                              PlanQuotaID = (Int32?)U.PlanQuotaID,
                                              ADSLproviderOther = U.ADSLproviderOther,
                                              TypeName = UT.TypeName,
                                              PlanDetailName = PND.PlanDetailName,
                                              PlanQuotaValue = (Int32?)PQ.PlanQuotaValue,
                                              PlanQuotaInterval = PQ.PlanQuotaInterval,
                                              RegisterDateTime = U.RegisterDateTime,
                                              IPAddress = U.IPAddress
                                          }).ToList();

            //get Order information
            var passModelOrder = (from U in db.Users
                                  join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID }
                                  join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID }
                                  join PN in db.PlanNames on new { ID = PND.PlanNamesID } equals new { ID = PN.ID }
                                  where
                                    U.ID == GetUserID
                                  select new SummaryModel()
                                  {
                                      ID = GetUserID,
                                      Name = PN.Name,
                                      ServicePhoneNumber = U.ServicePhoneNumber,
                                      PlanDetailName = PND.PlanDetailName,
                                      PlanQuotaValue = PQ.PlanQuotaValue,
                                      PlanQuotaInterval = PQ.PlanQuotaInterval,
                                      SetupCost = PQ.SetupCost,
                                      Price = PND.Price,
                                      TotalCost = (System.Decimal?)((PND.Price * PQ.PlanQuotaValue) + PQ.SetupCost)
                                  }).SingleOrDefault();


            //get order Extra information
            passModelOrder.listSummaryModel = from SEDA in db.SubExtrasDetailAssignToUsers
                                              join SED in db.SubExtrasDetails on SEDA.SubExtrasDetailID equals SED.SubExtrasDetailID
                                              join SE in db.SubExtras on new { SubExtrasID = (Int32)SED.SubExtrasID } equals new { SubExtrasID = SE.SubExtrasID }
                                              join EPQU in db.ExtraPlanQuotaAssigntoUsers
                                                    on new { SED.SubExtrasDetailID, SEDA.UserID }
                                                equals new { EPQU.SubExtrasDetailID, EPQU.UserID }
                                              join EX in db.ExtraPlanQuotas on EPQU.ExtraPlanQuotaID equals EX.ExtraPlanQuotaID
                                              where
                                                SEDA.UserID == GetUserID
                                              select new SubExtraDetailModel()
                                              {

                                                  SubExtrasDetailID = (Int32)SEDA.SubExtrasDetailID,
                                                  SubExtrasDetailName = SED.SubExtrasDetailName,
                                                  SubExtrasDetailPrice = SED.SubExtrasDetailPrice,
                                                  SubExtrasName = SE.SubExtrasName,
                                                  SubExtrasSetupFee = EX.ExtraSetupCost,
                                                  ExtraPlanQuotaValue = EX.ExtraPlanQuotaValue,
                                                  ExtraPlanQuotaInterval = EX.ExtraPlanQuotaInterval,
                                              };
          
            passModelOrder.listSummaryHardwareModel=from SEDA in db.SubHardwareDetailAssignToUsers
                                         join SED in db.SubHardwaresDetails on SEDA.SubHardwaresDetailID equals SED.SubHardwareDetailID
                                         join SE in db.SubHardwares on new { SubHardwareID = (Int32)SED.SubHardwareID } equals new { SubHardwareID = SE.SubHardwareID }
                                          where
                                           SEDA.UserID == GetUserID
                                               select new SubHardwareDetailModel()
                                               {

                                                   SubHardwareDetailID = (Int32)SEDA.SubHardwaresDetailID,
                                                   SubHardwareDetailName = SED.SubHardwareDetailName,
                                                   SubHardwareDetailPrice = SED.SubHardwareDetailPrice,
                                                   SubHardwareName = SE.SubHardwareName,
                                                   Quantity = SEDA.Quantity,
                                                   SubHardwareDetail=SE.SubHardwareDetail
                                               };

            //get Agreement Text
            var PlanID = (int)defaultPlanID.getdefaultPlanId; //fixed 1 by default
            var passmodelAgree = new AgreementModel();



            if (Request.Cookies["MainCookie"] != null)
            {

                String Getvalue = Request.Cookies["MainCookie"].Value.ToString().Replace("%7C", "|").Replace("%20", " ");
                string[] GetValue1 = Getvalue.Split('|');

                string fValue = GetValue1[0].ToString();

                if (fValue != null)
                {
                    PlanID = Convert.ToInt32(fValue);
                    passmodelAgree.Agreement = (from p in db.PlanNames where p.ID == PlanID select p.Agreement).SingleOrDefault();
                }


            }

            passmodelAgree.ID = GetUserID;
            //get Dynamic Agreement Text
           

            List<int> lstSubExtrasDetailID = (from item in db.SubExtrasDetailAssignToUsers where item.UserID == GetUserID select item.SubExtrasDetailID).ToList();
            List<int?> lstsubextrasID = (from SE in db.SubExtrasDetails
                                         where lstSubExtrasDetailID.Contains(SE.SubExtrasDetailID)
                                         select SE.SubExtrasID
                                     ).ToList();
            passmodelAgree.listDynamicAgreement = from SE in db.SubExtras
                                                  where lstsubextrasID.Contains(SE.SubExtrasID)
                                                  select new DynamicAgreementModel()
                                                  {
                                                      Agreement = SE.Agreement,
                                                      SubExtrasname = SE.SubExtrasName
                                                  };

            List<int> lstSubExtrasDetailIDH = (from item in db.SubHardwareDetailAssignToUsers where item.UserID == GetUserID select item.SubHardwaresDetailID).ToList();
            List<int?> lstsubextrasIDH = (from SE in db.SubHardwaresDetails
                                          where lstSubExtrasDetailIDH.Contains(SE.SubHardwareDetailID)
                                          select SE.SubHardwareID
                                     ).ToList();
            passmodelAgree.listDynamicAgreementHardware = from SE in db.SubHardwares
                                                 where lstsubextrasIDH.Contains(SE.SubHardwareID)
                                                 select new DynamicAgreementModel()
                                                 {
                                                     Agreement = SE.Agreement,
                                                     SubHardwareName = SE.SubHardwareName
                                                 };

            //If User want to change the plan , the we will send him mail regarding the change in plan.
            if (Request.Cookies["ckChangePlan"] != null) //User is login from  I'm already with Everynet 
            {
                //User have already complete whole signup process
                if (Request.Cookies["ckChangePlan"].Value.ToString() == "1" && checkUserPasswordExists == true)
                {
                    //send mail to user that your plan have changed.
                    try
                    {
                        UserMailer.PlanChange(getUserEmail, "Plan change Confirmation", message, passModel, passModelOrder, passmodelAgree).Send();
                    }
                    catch { }
                }
            }

            if (checkUserPasswordExists == null || checkUserPasswordExists == false) //If user password not exists
            {
                #region[update Complete Registered]
                //update CompleteRegistered in the database.
                User dbUser = new User { ID = model.ID };
                db.Users.Attach(dbUser);
                dbUser.CompleteRegistered = true;
                db.SaveChanges();
                #endregion

                try
                {
                    UserMailer.Registration(getUserEmail, "Complete Registration Confirmation", message, passModel, passModelOrder, passmodelAgree).Send();
                    // If WHMCS is not installed , it will show error.

                    InsertValuesIntoWHMCS(GetUserID);
                }
                catch { }
            }
            return View("OrderComplete");
        }
        #endregion

        #region Common Functions
        public SelectListItem[] getTitles()
        {
            return new[]
        {
           new SelectListItem { Value = "mr", Text = "Mr" },
           new SelectListItem { Value = "mrs", Text = "Mrs" },
           new SelectListItem { Value = "ms", Text = "Ms" },
           new SelectListItem { Value = "dr", Text = "Dr" },
           new SelectListItem { Value = "sir", Text = "Sir" },
           new SelectListItem { Value = "prof", Text = "Prof" },
           new SelectListItem { Value = "lt", Text = "It" },
           new SelectListItem { Value = "rev", Text = "Rev" },
           new SelectListItem { Value = "lady", Text = "Lady" },
           new SelectListItem { Value = "dame", Text = "Dame" },
           new SelectListItem { Value = "eldr", Text = "Eldr" },
           new SelectListItem { Value = "maj", Text = "Maj" },
           new SelectListItem { Value = "cptn", Text = "Ctn" },
           new SelectListItem { Value = "pstr", Text = "Pstr" },
           new SelectListItem { Value = "bshp", Text = "Bshp" }
        };

        }

        public string GenerateRandomPassword()
        {
            string allowedChars = "";
            //allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
            //allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
            //allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";

            allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z,";
            allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,";
            allowedChars += "2,3,4,5,6,7,8,9";

            char[] sep = { ',' };
            string[] arr = allowedChars.Split(sep);
            string passwordString = "";
            string temp = "";
            Random rand = new Random();
            for (int i = 0; i < 8; i++)
            {
                temp = arr[rand.Next(0, arr.Length)];
                passwordString += temp;
            }

            return passwordString;
        }

        //check Valid User
        public int checkUserValid(Int64 userID)
        {
            int returnValue = 0;
            var getUserPassword = (from p in db.Users where p.ID == userID select p.Password).SingleOrDefault();
            if (Session["userPassword"] != null)
            {
                if (getUserPassword == null) //fetch password is null
                {
                    returnValue = -2;
                }
                else // if "session value" match with "user id get password value"--then valid user
                {
                    if (getUserPassword.ToString() == Session["userPassword"].ToString().Trim())
                    {
                        returnValue = 1;
                    }
                }
            }
            else //session is null
            {
                if (getUserPassword == null) //fetch password is null
                {
                    returnValue = -2;
                }
                else
                {
                    returnValue = -1;
                }
            }
            return returnValue;
        }
        #endregion

        #region [Validations]
        [HttpGet]
        public ActionResult CheckvalidationString(string matchValue)
        {
            var getResult = 0;
            Regex RgxUrl = new Regex("[^a-z A-Z0-9]");
            if (!RgxUrl.IsMatch(matchValue))
            {
                if (matchValue.ToString().Length <= 50 && matchValue.ToString().Length >= 2) //max 50 and min 2 characters.
                {
                    getResult = 1;
                }

            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult CheckvalidationInteger(string matchValue)
        {
            var getResult = 0;
            Regex RgxUrl = new Regex("[^0-9]");
            if (!RgxUrl.IsMatch(matchValue))
            {
                if (matchValue.ToString().Length == 10)
                {
                    getResult = 1;
                }
            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult CheckvalidationEmail(string matchValue)
        {
            var getResult = 0;

            const String pattern = @"^([0-9a-zA-Z]" + //Start with a digit or alphabate
                                  @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continues or ending +-_. chars in email
                                  @")+" +
                                  @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

            Regex RgxUrl = new Regex(pattern);
            if (RgxUrl.IsMatch(matchValue))
            {
                getResult = 1;

                //We need to check this Email Id already exists in the database.
                //case 1: User Register First Time
                var UserID = 0;
                var checkEmail = (from e in db.Users where e.Email == matchValue select e.ID).SingleOrDefault();
                if (Request.Cookies["ckUserID"] != null)
                {
                    UserID = Convert.ToInt32(Request.Cookies["ckUserID"].Value);
                    checkEmail = (from e in db.Users where e.Email == matchValue && e.ID != UserID select e.ID).SingleOrDefault();
                }
                if (checkEmail != 0)
                {
                    getResult = 2;
                }
               


            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult CheckvalidationAddress(string matchValue)
        {
            var getResult = "Currently we are unable to perform an automatic address qualification,please proceed with your application and a sales representative will contact you.";
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult CheckvalidationTitle(string matchValue)
        {
            var getResult = 0;
            String strCompare = "mr,mrs,ms,dr,sir,prof,lt,rev,lady,dame,eldr,maj,cptn,pstr,bshp";

            if (strCompare.Contains(matchValue))
            {
                getResult = 1;
            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult CheckvalidationAdsl(string matchValue)
        {
            var getResult = 0;
            if (!String.IsNullOrEmpty(matchValue))
            {
                getResult = 1;
            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult CheckvalidationUsername(string matchValue)
        {
            var UserID = 0;
            UserID = Convert.ToInt32(Request.Cookies["ckUserID"].Value);
            var getResult = 0;

            //check length of characters(Min. 6 characters)
            var checkength = matchValue.Length;

            if (checkength > 0)
            {
                //check first character is a interger or string
                var checkcharacter = matchValue.Substring(0, 1);

                if (Regex.IsMatch(checkcharacter, "^[A-Za-z]"))
                {
                    if (checkength >= 6)
                    {
                        //check username already exists in the database
                        //var checkuser = (from e in db.Users where e.UserName == matchValue && e.ID != UserID select e.ID).SingleOrDefault();
                        var checkuser = 0;
                        if (checkuser == 0) //Username with this name not exists in the database. 
                        {
                            getResult = 1;
                        }
                    }
                }
            }
            return Json(getResult, JsonRequestBehavior.AllowGet);
        }

        //remote Validation for username
        public JsonResult ValidateUserName(string UserName)
        {
            var UserID = 0;
            if (Request.Cookies["ckUserID"] != null)
            {
                UserID = Convert.ToInt32(Request.Cookies["ckUserID"].Value);
            }
            var checkuser = (from e in db.Users where e.UserName == UserName && e.ID != UserID select e.ID).SingleOrDefault();
            if (checkuser == 0)//Username with this name not exists in the database. 
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("UserName already taken!", JsonRequestBehavior.AllowGet);
            }
        }

        //remote Validation for Contact Email Address
        public JsonResult ValidateContactEmailAddress(string Email)
        {
            var UserID = 0;
            if (Request.Cookies["ckUserID"] != null)
            {
                UserID = Convert.ToInt32(Request.Cookies["ckUserID"].Value);
            }
            var checkEmail = (from e in db.Users where e.Email == Email && e.ID != UserID select e.ID).SingleOrDefault();
            if (checkEmail == 0)//Username with this name not exists in the database. 
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("Email already taken!", JsonRequestBehavior.AllowGet);
            }
        }

        #endregion


        #region [Forget Password]
        public ActionResult ForgetPassword()
        {

            var model = new ForgetPasswordModel();
            return View("ForgetPassword", model);
        }

        [HttpPost, Recaptcha.RecaptchaControlMvc.CaptchaValidator]
        public string ForgetPasswordMail(ForgetPasswordModel model, bool captchaValid, string captchaErrorMessage)
        {
            //check Email Exists in Database Or Not
            var checkEmail = (from p in db.Users where p.Email == model.Email select p.ID).FirstOrDefault();
            String returnValue = "1";
            if (checkEmail != 0)
            {

                if (ModelState.IsValid)
                {
                    //check Captcha is Valid
                    if (captchaValid)
                    {
                        var getPassword = (from p in db.Users where p.ID == checkEmail select p.Password).FirstOrDefault();
                        returnValue = "1";
                        string message = getPassword;
                        try
                        {
                            UserMailer.ForgotPassword(model.Email, "Forgot Password", message).Send();
                        }
                        catch { }
                    }
                    else
                    {
                        ModelState.AddModelError("", captchaErrorMessage);
                        returnValue = "2";
                    }
                }
            }
            else
            {
                returnValue = "3";
            }
            return returnValue;
        }


        #endregion

        #region [SignIn]
        public ActionResult SignIn()
        {
            var model = new signInModel();
            return View("SignIn", model);
        }
        public ActionResult CheckUser(signInModel model)
        {
            //check this is a valid email and password:
            var checkUserIdbyUsernamePassword = (from p in db.Users where p.Email == model.Email && p.Password == model.Password select p.ID).FirstOrDefault();

            if (checkUserIdbyUsernamePassword != 0) //Valid User
            {
                return RedirectToAction("ValidUser", new { id = checkUserIdbyUsernamePassword });
            }
            else
            {
                ModelState.AddModelError("", "Invalid Email and Password");
                return View("SignIn"); //InValid User
            }
        }

        public ActionResult ValidUser(Int64 id)
        {
            var model = (from p in db.Users
                         where p.ID == id
                         select new OrdersModel()
                         {
                             FirstName = p.FirstName,
                             LastName = p.LastName
                         }).FirstOrDefault();
            model.OrderStatusCompleteRegistered = (from p in db.Users where p.ID == id select p.CompleteRegistered).FirstOrDefault();

            model.OrderStatus = (from p in db.Orders where p.UserID == id select p.OrderStatus).FirstOrDefault();
            model.ID = (from p in db.Users where p.ID == id select p.ID).FirstOrDefault();
            return View("UserStatus", model);
        }
        #endregion

        public static string Mainusername = ConfigurationManager.AppSettings["WhmcsUsername"].ToString();
        public static string Mainpassword = ConfigurationManager.AppSettings["WhmcsPassword"].ToString();
        public static string path = ConfigurationManager.AppSettings["WhmcsPath"].ToString();

        #region[Insert Values into WHMCS]
        public void InsertValuesIntoWHMCS(Int64 userID)
        {
            // Instantiate the WebClient object
            WebClient WHMCSclient = new WebClient();
            #region [Get UserData from Sql Database with UserID]
            //Get Data from Sql Database with UserID
            var model = new signUpModel();
            model = (from U in db.Users
                     where U.ID == userID
                     select new signUpModel()
                     {
                         FirstName = U.FirstName,
                         LastName = U.LastName,
                         MobileNumber = U.MobileNumber,
                         Email = U.Email,
                         ServiceAddress = U.ServiceAddress,
                         ServicePhoneNumber = U.ServicePhoneNumber,
                         Password = U.Password,
                         RegisterDateTime = U.RegisterDateTime,
                         IPAddress = U.IPAddress
                     }).SingleOrDefault();
            #endregion
            #region[Save Data to Client Table]
            // Prepare a Name/Value collection to hold the post values
            NameValueCollection form = new NameValueCollection();
            form.Add("username", Mainusername);
            form.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            form.Add("action", "addclient");// action performed by the API:Functions
            form.Add("firstname", model.FirstName);
            form.Add("lastname", model.LastName);
            form.Add("companyname", "");
            form.Add("email", model.Email);
            form.Add("address1", model.ServiceAddress);
            if (model.ServicePhoneNumber != null)
            {
                form.Add("customfield[1]", model.ServicePhoneNumber.ToString()); //Service Phone Number
            }
            else
            {
                form.Add("customfield[1]", ""); //Service Phone Number
            }

            /* Int32? getplanQuotaID1 = (from e in db.Users where e.ID == userID select e.PlanQuotaID).SingleOrDefault();
             String getMainPlanQuotaValue1 = Convert.ToString((from e in db.PlanQuotas where e.PlanQuotaID == getplanQuotaID1 select e.PlanQuotaValue).SingleOrDefault());
           
             if(!String.IsNullOrEmpty(getMainPlanQuotaValue1))
             {
             form.Add("customfield[5]", getMainPlanQuotaValue1.ToString());
             //form.Add("customfield[3]", getMainPlanQuotaValue1.ToString());
             //form.Add("customfield3", getMainPlanQuotaValue1.ToString());
             //form.Add("customfields[3]", getMainPlanQuotaValue1.ToString());
             DateTime dt = new DateTime();
             dt = DateTime.Now.AddMonths(Convert.ToInt32(getMainPlanQuotaValue1));
             String getfinalDate = dt.ToString();
             form.Add("customfield[6]", getfinalDate);
             }*/

            form.Add("city", "");
            form.Add("state", "");
            form.Add("postcode", "");
            form.Add("country", "");
            form.Add("phonenumber", model.MobileNumber.ToString());
            form.Add("password2", model.Password);
            form.Add("datecreated", model.RegisterDateTime.ToString());
            form.Add("ip", model.IPAddress);
            form.Add("currency", "");
            form.Add("skipvalidation", 1.ToString());
            Byte[] responseData = WHMCSclient.UploadValues(path, form);
            string getCustomerIDfromWHMCS = string.Empty;
            string splitFullString = Encoding.ASCII.GetString(responseData);
            if (!String.IsNullOrEmpty(splitFullString))
            {
                string[] splitwords = splitFullString.Split(';');
                string[] subsplitwords = splitwords[1].Split('=');
                getCustomerIDfromWHMCS = subsplitwords[1];
            }
            #endregion
            #region[Save Data to Contact Table]
            if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            {
                NameValueCollection formContact = new NameValueCollection();
                formContact.Add("username", Mainusername);
                formContact.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formContact.Add("action", "addcontact");// action performed by the API:Functions
                formContact.Add("clientid", getCustomerIDfromWHMCS); //Current Id of the user that is Inserted in WHMCS.
                formContact.Add("firstname", model.FirstName);
                formContact.Add("lastname", model.LastName);
                formContact.Add("email", model.Email);
                formContact.Add("address1", model.ServiceAddress);
                formContact.Add("phonenumber", model.MobileNumber.ToString());
                formContact.Add("password2", model.Password);
                Byte[] responseDataContact = WHMCSclient.UploadValues(path, formContact);
            }
            #endregion
            #region[Save Data to Order Table]
            if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            {
                NameValueCollection formOrder = new NameValueCollection();
                formOrder.Add("username", Mainusername);
                formOrder.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formOrder.Add("action", "addorder");// action performed by the API:Functions
                formOrder.Add("clientid", getCustomerIDfromWHMCS);
                formOrder.Add("paymentmethod", "eway");
                //to get the products attach with the User ID
                //Get the product ids in comma separated String.(Main Product ID concatenate with Extras IDS)
                //Main Product
                String getMainProductValue = Convert.ToString((from e in db.Users where e.ID == userID select e.PlanNamesDetailID).SingleOrDefault());
                Int32? getplanQuotaID = (from e in db.Users where e.ID == userID select e.PlanQuotaID).SingleOrDefault();
                String getMainPlanQuotaValue = Convert.ToString((from e in db.PlanQuotas where e.PlanQuotaID == getplanQuotaID select e.PlanQuotaValue).SingleOrDefault()); ;
                //Get Quota in List
                List<SubExtrasDetail> lstQuota = new List<SubExtrasDetail>();
                lstQuota = (from EPQU in db.ExtraPlanQuotaAssigntoUsers
                            join EPQ in db.ExtraPlanQuotas on EPQU.ExtraPlanQuotaID equals EPQ.ExtraPlanQuotaID
                            where
                              EPQU.UserID == userID
                            select new SubExtrasDetail()
                            {
                                SubExtrasDetailID = (Int32)EPQU.SubExtrasDetailID,
                                ExtraPlanQuotaValue = EPQ.ExtraPlanQuotaValue
                            }).ToList();
                //Get Extras in List
                List<SubExtrasDetail> lst = new List<SubExtrasDetail>();
                lst = (from e in db.SubExtrasDetailAssignToUsers
                       where e.UserID == userID
                       orderby e.SubExtrasDetailID
                       select new SubExtrasDetail() { SubExtrasDetailID = e.SubExtrasDetailID }).ToList();
                //Foreach Extras
                foreach (var item in lst)
                {
                    getMainProductValue += "," + item.SubExtrasDetailID;
                    //Foreach Quotas
                    foreach (var itemQ in lstQuota)
                    {
                        if (itemQ.SubExtrasDetailID == item.SubExtrasDetailID)
                        {
                            getMainPlanQuotaValue += "," + itemQ.ExtraPlanQuotaValue;
                        }
                    }

                }
                //Hardwares Start
                List<SubHardwaresDetail> lstH = new List<SubHardwaresDetail>();
                lstH = (from e in db.SubHardwareDetailAssignToUsers
                       where e.UserID == userID
                       orderby e.SubHardwaresDetailID
                        select new SubHardwaresDetail() { SubHardwareDetailID = e.SubHardwaresDetailID }).ToList();
                foreach (var itemH in lstH)
                {
                    getMainProductValue += "," + itemH.SubHardwareDetailID;
                }
               //Hardware End

                var primeArray = getMainProductValue.Split(',');
                var primeArrayQuota = getMainPlanQuotaValue.Split(',');
                List<string[]> arrays = new List<string[]>();
                for (int i = 0; i < primeArray.Length; i++)
                {
                    var first = primeArray[i];
                    //var Quota = Convert.ToInt32(primeArrayQuota[i]);
                    formOrder.Add("pid[" + (i + 1) + "]", first.ToString());

                    //check PID is a Hardware or not, If Hardware then fixed or one time payment.

                    List<SubHardwaresDetail> lstHCheck = new List<SubHardwaresDetail>();
                    lstHCheck = (from e in db.SubHardwareDetailAssignToUsers
                            where e.UserID == userID
                            orderby e.SubHardwaresDetailID
                            select new SubHardwaresDetail() { SubHardwareDetailID = e.SubHardwaresDetailID }).ToList();
                    var checkID = "";
                    foreach (var itemHCheck in lstHCheck)
                    {
                        if (itemHCheck.SubHardwareDetailID.ToString() == first.ToString())
                        {
                            checkID = "1";
                        }
                    }
                    if (checkID == "")
                    {
                        formOrder.Add("billingcycle[" + (i + 1) + "]", "monthly");
                    }
                    else
                    {
                        formOrder.Add("billingcycle[" + (i + 1) + "]", "onetime");
                    }
                }
                Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formOrder);

               
            }
            #endregion

            /*formOrder.Add("customfield[3]", "monthlynext");
                    formOrder.Add("customfields[3]", "monthlynext");
                    formOrder.Add("customfield3", "monthlynext");*/
            /* int value = Quota;
            if (i == 0)
           {
               formOrder.Add("customfield[5]", value.ToString());
               DateTime dt = new DateTime();
               dt = DateTime.Now.AddMonths(value);
               String getfinalDate = dt.ToString();
               formOrder.Add("customfield[6]", getfinalDate);

           }*/
            /* switch (value)
            {
                case 1:
                    formOrder.Add("customfield[3]", "monthly");
                    formOrder.Add("customfield[5]", "monthly");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "monthly");
                    break;
                case 3:
                    formOrder.Add("customfield[3]", "quarterly");
                    formOrder.Add("customfield[5]", "quarterly");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "quarterly");
                    break;
                case 6:
                    formOrder.Add("customfield[3]", "semiannually");
                    formOrder.Add("customfield[5]", "semiannually");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "semiannually");
                    break;
                case 12:
                    formOrder.Add("customfield[3]", "annually");
                    formOrder.Add("customfield[5]", "annually");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "annually");
                    break;
                case 24:
                    formOrder.Add("customfield[3]", "biennially");
                    formOrder.Add("customfield[5]", "biennially");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "biennially");
                    break;
                case 36:
                    formOrder.Add("customfield[3]", "triennially");
                    formOrder.Add("customfield[5]", "triennially");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "triennially");
                    break;
                default:
                    formOrder.Add("customfield[3]", "monthly");
                    formOrder.Add("customfield[5]", "monthly");
                    //formOrder.Add("customfield[" + (i + 1) + "]", "monthly");
                    break;

            }*/

        }

        public class SubExtrasDetail
        {
            public Int32 SubExtrasDetailID { get; set; }
            public Int32 ExtraPlanQuotaValue { get; set; }
        }
        public class SubHardwaresDetail
        {
            public Int32 SubHardwareDetailID { get; set; }
        }
        #endregion

        #region [Sign up Test]
        public ActionResult signupTest()
        {
            return View("signupTest");
        }
        #endregion


        #region change of Plan Quota According to Plans
        public ActionResult changeMainQuotawithSubPlanID(int ID)
        {
            var modelj = from d in db.PlanQuotas
                         orderby d.PlanNamesDetailID,d.PlanQuotaValue
                         where d.PlanNamesDetailID == ID
                         select new { d.PlanQuotaID, d.PlanQuotaValue, d.PlanQuotaInterval, d.SetupCost, d.PlanNamesID, d.VisiblePublic, d.PlanNamesDetailID,d.EarlyExitFee,d.Comment };
            return Json(modelj, JsonRequestBehavior.AllowGet);
        }
       #endregion

        #region change of extra Plan Quota According to Plans
       
        public ActionResult changeExtrasMainQuota(int ID)
        {

            var model = from ext in db.ExtraPlanQuotas
                        orderby ext.SubExtrasDetailID,ext.ExtraPlanQuotaValue
                        where ext.SubExtrasDetailID == ID
                        select new { ext.ExtraPlanQuotaID, ext.ExtraPlanQuotaValue, ext.ExtraPlanQuotaInterval, ext.ExtraSetupCost, ext.SubExtrasID, ext.VisiblePublic, ext.SubExtrasDetailID };
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        #endregion

    }
}
